让诺言等待几秒钟再回来 [英] let promise wait a couple of seconds before return

查看:45
本文介绍了让诺言等待几秒钟再回来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回诺言的函数.在此功能中,我们调用第三方供应商通过其服务器发送一些推送通知.

I'm having a function returning a promise. In this function, we call a third party vender to send some push notification through their server.

看起来像

apiGetLoggedInUser.then(
  user => {
    return sendMessage(user.name);
  }
)

但是,我们决定等待3秒才真正调用此sendMessage函数.但是,我们不希望更改sendMessage,因为它已提供.

However the thing is we decided to wait for 3 seconds before we really call this sendMessage function. However we'd prefer not to change sendMessage since it's provided.

我想知道在这种情况下如何真正地执行等待"部分,因为promise用于删除同步"操作.

I'm wondering how to really do the "wait" part in this scenario since promise is used to remove "sync" operations.

我理解正确吗?我该怎么办?

Am I understanding correctly? What shall I do?

推荐答案

在链中插入另一个承诺,该承诺会延迟下一个承诺:

Insert another promise in the chain which delays the next one:

apiGetLoggedInUser
    .then(user => {
        return new Promise(resolve => setTimeout(() => resolve(user), 3000));
    })
    .then(user => sendMessage(user.name))

这篇关于让诺言等待几秒钟再回来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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