3 回答

TA貢獻1817條經驗 獲得超6個贊
錯誤不是指myfunction而是start。
async function start() {
....
const result = await helper.myfunction('test', 'test');
}
// My function
const myfunction = async function(x, y) {
return [
x,
y,
];
}
// Start function
const start = async function(a, b) {
const result = await myfunction('test', 'test');
console.log(result);
}
// Call start
start();
我利用這個問題的機會來告訴你一個已知的反模式的使用await方法:return await。
錯誤
async function myfunction() {
console.log('Inside of myfunction');
}
// Here we wait for the myfunction to finish
// and then returns a promise that'll be waited for aswell
// It's useless to wait the myfunction to finish before to return
// we can simply returns a promise that will be resolved later
async function start() {
// useless await here
return await myfunction();
}
// Call start
(async() => {
console.log('before start');
await start();
console.log('after start');
})();
正確
async function myfunction() {
console.log('Inside of myfunction');
}
// Here we wait for the myfunction to finish
// and then returns a promise that'll be waited for aswell
// It's useless to wait the myfunction to finish before to return
// we can simply returns a promise that will be resolved later
async function start() {
return myfunction();
}
// Call start
(async() => {
console.log('before start');
await start();
console.log('after start');
})();

TA貢獻1799條經驗 獲得超9個贊
當我收到此錯誤時,事實證明我在“異步”函數(shù)中調用了map函數(shù),因此此錯誤消息實際上是指未標記為“異步”的map函數(shù)。通過從map函數(shù)中取消“ await”調用并提出了一些其他實現(xiàn)預期行為的方法,我解決了這個問題。
var myfunction = async function(x,y) {
....
someArray.map(someVariable => { // <- This was the function giving the error
return await someFunction(someVariable);
});
}

TA貢獻1830條經驗 獲得超9個贊
真正的問題是您需要了解異步/等待如何在這里工作。錯誤在于start function()
您需要定義功能Async函數(shù)的使用await作為
await 使用承諾/未來/任務返回方法/功能
async 將方法/功能標記為能夠使用等待。
Await實際上是在執(zhí)行promise / resolve的相同過程,并且由于該功能是async其他任務,因此正在并行處理
有關更多信息,請參考 MDN DOCS
async function foo(){
let myAsyncCall = await .... ('/endpoint') // hitting on some api
console.log(myAsyncCall) // myAsyncCall will log out whenever the request get resolved
}
foo()
添加回答
舉報