繁体   English   中英

如何在node.js中同步调用api?

[英]How to make synchronous api calls in node js?

当我运行这段代码时:

import fetch from 'node-fetch';

const url = "https://jsonplaceholder.typicode.com/todos/1";
const get = async () => {
    try {
        let response = await fetch(url);
        let res = await response.json();
        console.log(res);
    } catch (err) {
        console.error(err);
    }
};

(async function () {
    await get();
})();

console.log("I am outside");

我得到以下 output:

$ node index.js
I am outside
{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }

为什么我没有以相反的顺序获得 output,即使我等待异步函数?

这是等待:

await get()

但这不是:

(async function(){
  await get()
})();

如果您使用的是支持顶级await的 Node 版本,则可以等待它:

await (async function(){
  await get()
})();

或者跟进 Promise 回拨:

(async function(){
  await get()
})().then(() => {
  console.log('I am outside');
});

或者,您可以将您的逻辑移动到 IIFE 中:

(async function(){
  await get();
  console.log('I am outside');
})();

这部分是异步的

( async function(){
    await get()
})();

我可以想到两种方法让文本首先显示;

  1. 在异步函数调用之前移动它
  2. 将其移动到 function 电话中;

根据我的经验,正如 David 所说,您应该将要运行的代码放在前面定义的函数的 scope 中的异步代码之后。scope 中的所有同步代码都将首先运行

因为这个 function

( async function(){
    await get()
})();

异步运行,所以 console.log 将首先打印如果你想先运行get() ,你应该做类似的事情

( async function() {
  await get();
  console.log('I am outside')
})

或另一个

( async function() {
  await get();
}).then( () => {
  console.log('I am outside');
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM