3 回答

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
錯(cuò)誤不是指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();
我利用這個(gè)問(wèn)題的機(jī)會(huì)來(lái)告訴你一個(gè)已知的反模式的使用await方法:return await。
錯(cuò)誤
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貢獻(xiàn)1942條經(jīng)驗(yàn) 獲得超3個(gè)贊
當(dāng)我收到此錯(cuò)誤時(shí),事實(shí)證明我在“異步”函數(shù)中調(diào)用了map函數(shù),因此此錯(cuò)誤消息實(shí)際上是指未標(biāo)記為“異步”的map函數(shù)。通過(guò)從map函數(shù)中取消“ await”調(diào)用并提出了一些其他實(shí)現(xiàn)預(yù)期行為的方法,我解決了這個(gè)問(wèn)題。
var myfunction = async function(x,y) {
....
someArray.map(someVariable => { // <- This was the function giving the error
return await someFunction(someVariable);
});
}

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超7個(gè)贊
真正的問(wèn)題是您需要了解異步/等待如何在這里工作。錯(cuò)誤在于start function()
您需要定義功能Async函數(shù)的使用await作為
await 使用承諾/未來(lái)/任務(wù)返回方法/功能
async 將方法/功能標(biāo)記為能夠使用等待。
Await實(shí)際上是在執(zhí)行promise / resolve的相同過(guò)程,并且由于該功能是async其他任務(wù),因此正在并行處理
有關(guān)更多信息,請(qǐng)參考 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()
添加回答
舉報(bào)