繁体   English   中英

JavaScript 如何调用 web API?

[英]How does JavaScript call web APIs?

据我所知,当我调用 web API 时, JavaScript 的正常行为就像 setTimeout 4 次一样:

它应该调用第一个然后将其添加到队列中等待调用堆栈为空.. 重复它将对所有其他 api 执行相同的操作.. 所以第二个 function 应该等到第一个执行然后开始被调用。 . 这意味着它应该花费第二个 function 2 秒或更多,然后它应该花费第三个 function 或更多......等等......


我错过了什么?

setTimeOut javascript web api

var TimeOutOnTimeOut = () => {
   setTimeout(() => {
       console.log("Like this!");
       TimeOutOnTimeOut();
    }, 3000);
};
    
TimeOutOnTimeOut();

他们都会同时调用,但是你可以在第一个完成后调用下一个。

注意:由于我无法添加评论,因此我发布了此答案。

const sleep = (timeout) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            // perform some task here
            resolve(true);
        }, timeout);
    });
};

async () => {
    // in asynchronous function
    await sleep(1000);
    // do something after code returns
};
// in global scope or synchronous
sleep(1000).then(() => {
    // callback
});

尝试使用异步等待并等待每个操作完成。

 const sleep = (ms) => new Promise(e => setTimeout(e, ms)); const logSeconds = async () => { await sleep(1000); console.log(new Date().toLocaleTimeString()); } const main = async () => { await logSeconds(); await logSeconds(); await logSeconds(); } main()

暂无
暂无

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

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