j.d*_*doe 77 javascript node.js
我写了这段代码 lib/helper.js
var myfunction = async function(x,y) {
....
reutrn [variableA, variableB]
}
exports.myfunction = myfunction;
Run Code Online (Sandbox Code Playgroud)
然后我试着在另一个文件中使用它
var helper = require('./helper.js');
var start = function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
Run Code Online (Sandbox Code Playgroud)
我收到了一个错误
"await仅在异步函数中有效"
有什么问题?
Gré*_*EUT 92
错误不是指,myfunction
而是指start
.
async function start() {
....
const result = await helper.myfunction('test', 'test');
}
Run Code Online (Sandbox Code Playgroud)
编辑
// 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();
Run Code Online (Sandbox Code Playgroud)
Sat*_*hak 16
要使用await
,它的执行上下文需要async
在本质上
正如它所说,在做任何事情之前,您需要先定义executing context
您愿意执行await
任务的性质。
只需放在您的任务将在其中执行async
的fn
声明之前async
。
var start = async function(a, b) {
// Your async task will execute with await
await foo()
console.log('I will execute after foo get either resolved/rejected')
}
Run Code Online (Sandbox Code Playgroud)
解释:
在你的问题,你导入的是method
这是asynchronous
在本质上,将并行执行。但是您尝试执行该async
方法的位置位于execution context
您需要定义async
以使用的不同方法中await
。
var helper = require('./helper.js');
var start = async function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
Run Code Online (Sandbox Code Playgroud)
想知道引擎盖下发生了什么
await
消耗承诺/未来/任务返回方法/函数并将方法/函数async
标记为能够使用等待。
此外,如果您熟悉promises
,await
实际上正在执行相同的承诺/解决过程。创建一个承诺链并在resolve
回调中执行你的下一个任务。
有关更多信息,您可以参考MDN 文档。
gia*_*ise 15
如果您正在编写 Chrome 扩展程序,并且您的代码在根目录中出现此错误,则可以使用以下“解决方法”修复该错误:
async function run() {
// Your async code here
const beers = await fetch("https://api.punkapi.com/v2/beers");
}
run();
Run Code Online (Sandbox Code Playgroud)
基本上,您必须将异步代码包装在 an 中async function
,然后调用该函数而不等待它。
Joh*_*ord 10
当我收到此错误时,事实证明我在“异步”函数中调用了map函数,因此此错误消息实际上是指未标记为“异步”的map函数。通过从map函数中取消“ await”调用并提出了一些其他实现预期行为的方法,我解决了这个问题。
var myfunction = async function(x,y) {
....
someArray.map(someVariable => { // <- This was the function giving the error
return await someFunction(someVariable);
});
}
Run Code Online (Sandbox Code Playgroud)
在更高版本的nodejs(> = 14)中,允许{ "type": "module" }
在文件扩展名中指定package.json
或使用文件扩展名top等待.mjs
。
https://www.stefanjudis.com/today-i-learned/top-level-await-is-available-in-node-js-modules/
小智 5
我遇到了同样的问题,以下代码块给出了相同的错误消息:
repositories.forEach( repo => {
const commits = await getCommits(repo);
displayCommit(commits);
});
Run Code Online (Sandbox Code Playgroud)
问题是 getCommits() 方法是异步的,但我将参数 repo 传递给它,该参数也是由 Promise 生成的。所以,我不得不像这样添加 async 这个词:async(repo) 然后它开始工作:
repositories.forEach( async(repo) => {
const commits = await getCommits(repo);
displayCommit(commits);
});
Run Code Online (Sandbox Code Playgroud)