ES6-决定是反对还是答应 [英] ES6 - decide if object or promise

查看:115
本文介绍了ES6-决定是反对还是答应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单而优雅的方法来确定javascript(es6)中的变量是promise还是object?

Is there a simple and elegant way to determinate if variable is promise or object in javascript (es6)?

我有一个变量

let payment;

并且一次在应用程序中,它可以是promise或具有真实值的对象.我知道我可以测试它包含的一些属性,例如

and at one time in app, it can be either promise or object with real values. I know I can test it it contains some properties like

if (payment.amount)

但这对我来说似乎不是一个优雅的解决方案,因为属性(数据结构)可以随时间变化.直到现在我在用

but this doesn't seems like an elegant solution to me, because properties (data structure) can change in time. Till now I was using

if (typeof payment === 'object')

但是我刚刚弄清楚,诺言基本上也是对象.因此,这种情况总是正确的.

but I've just figured out, that promises are basically also objects. So this condition is always true.

是否可以确定它是带有真实数据的承诺还是对象?

Is it possible to tell if it's a promise or object with real data?

推荐答案

检查其是否具有作为函数的属性then:

Check if it has a property then that is a function:

if(payment != null && typeof payment.then === 'function')
  // is a promise
else
  // is not a promise

据我所知,这是在考虑所有可能的promise实现的情况下检查某事物是否为promise(或类似promise的东西")的唯一正确方法.

As far as I know, this is the only proper way to check if something is a promise (or a "promise-like" thenable), taking into account all different possible promise implementations.

这篇关于ES6-决定是反对还是答应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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