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

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

问题描述

我想知道如何在API中支持 Promise 和回调。到目前为止,我已经阅读了一些文章来尝试实现,但是所有这些文章都使用deferred的延迟或第三方Promise库。我想使用Native ES Promises。我想知道如何实现这样的东西。请不要引用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.

推荐答案

没有进一步的上下文提问,并不完全确定预期结果是来自可能以外的功能。

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或Callbacks,没有延迟或外部Promise库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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