如何支持 API 调用以使用 Promise 或带有标准 Promise 的回调,没有延迟或外部 Promise 库? [英] How to support API calls to use a Promise or Callbacks with Standard Promises, no defers or external Promise Library?

查看:20
本文介绍了如何支持 API 调用以使用 Promise 或带有标准 Promise 的回调,没有延迟或外部 Promise 库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在 API 中支持 Promise 和回调.到目前为止,我已经阅读了几篇文章来尝试实现,但是所有这些文章都使用 deferred 或具有 Deferred 的第三方 Promise 库.我想使用原生 ES 承诺.我想知道如何实现这样的东西.请不要参考 Promisify 或任何第三方库,因为我实际上想实现这一点.函数签名如下:

I'm wondering how to support Promise's and Callbacks in an API. So far I've read through a few articles to try to implement however all these articles use deferred or a third party Promise library that has Deferred's. I want to use Native ES Promises. I wanted to know how to implement something like this. Please do not reference Promisify or any third party library as I actually want to implement this. The function signature is like the following:

function (callback) {
  if (callback) {
    // wrap callback and return Promise thats thenable
  }
  // return a Promise thats thenable
}

这是我脑海中应该如何进行的事情,但我不确定如何实施.如果您有经验或知道如何做到这一点,请回复,因为我想学习.

This is something I had in my head for how something should go but I'm not sure how to implement. If you have experience or know how to do this please reply as I'd like to learn.

推荐答案

没有问题的进一步上下文,不能完全确定预期结果来自thenable"以外的函数.

Without further context to Question, not entirely certain what expected result is from function other than "thenable".

最简单的方法是使用 Promise.resolve()Promise.reject();尽管您也可以使用 Promise.all()Promise.race()new Promise() 构造函数来返回thenable".

The simplest approach would be to utilize Promise.resolve() or Promise.reject(); though you could also use Promise.all(), Promise.race() or new Promise() constructor to return a "thenable".

function fn(callback) {
  if (callback) {
    // wrap callback and return Promise thats thenable
    return Promise.resolve(callback())
  }
  // return a Promise thats thenable
  return Promise.resolve()
}

fn().then(function(data) {
  console.log("no callback passed:", data); // `data` : `undefined`
})

fn(function() {return 123})
.then(function(data) {
  console.log("callback passed:", data); // `data`: `123`
})

这篇关于如何支持 API 调用以使用 Promise 或带有标准 Promise 的回调,没有延迟或外部 Promise 库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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