在Node.js 7.6+中有没有可能使用内置await而不异步的方法? [英] Is there any possible way to use built-in await without async in Node.js 7.6+?

查看:55
本文介绍了在Node.js 7.6+中有没有可能使用内置await而不异步的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node.js程序员.在Node.js 7.6发布之前,我使用了模块' asyncawait '来让我的代码进入async-await状态风格.编码样式如下:

I'm a Node.js programmer. Before Node.js 7.6 released, I used the module 'asyncawait' to let my code in async-await style. The coding style is like below:

var async = require('asyncawait/async');
var await = require('asyncawait/await');

var getData = async(function(finder){
    return await(db.collection.findOne(finder));
});

var f = function(finder){
    return await(getData(finder));
};

try{
    let result = f({id: 1});
}catch(err){
}

Node.js 7.6发布后,async-await函数正式内置.但是async和await函数(或称它们为关键字?)似乎必须在一个函数中配对.如果我将代码更改为,

After Node.js 7.6 released, the async-await function is officially built-in. But the async and await functions(or call them keywords?) seemingly have to be paired in a function. If I change my code to,

var getData = async function(finder){
    return await db.collection.findOne(finder);
}

var f = function(finder){
    return await getData(finder);
};

try{
    let result = f({id: 1});
}catch(err){
}

无法识别"f"功能中的"await"关键字.除非我将代码更改为

The 'await' keyword in 'f' function cannot be recognized. Unless I change the code to,

var getData = async function(finder){
    return await db.collection.findOne(finder);
}

var f = async function(finder){
    return await getData(finder);
};

try{
    let result = await f({id: 1});
}catch(err){
}

代码将很乏味.有没有可能在函数中不使用异步的情况下使用内置等待?

The code will be tedious. Is there any possible way to use built-in await without async in a function?

推荐答案

等待只能在异步函数中使用.

Await can only be used inside async functions.

await表达式使异步函数执行暂停,等待 用于Promise的解决方案,并恢复异步功能 值解析后执行.然后返回已解析的 价值.如果该值不是Promise,则将其转换为已解决 答应.

The await expression causes async function execution to pause, to wait for the Promise's resolution, and to resume the async function execution when the value is resolved. It then returns the resolved value. If the value is not a Promise, it's converted to a resolved Promise.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

这篇关于在Node.js 7.6+中有没有可能使用内置await而不异步的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆