如何将基于回调的函数转换为基于Promise的函数?

时间:2017-08-31 00:09:54

标签: javascript reactjs amazon-ec2 ecmascript-6 promise

目前,AWS documentation的功能类似于

describeInstances(params = {}, callback) ⇒ AWS.Request

我使用它的代码看起来像

let getAwsInstancesInfo = function () {
    console.log("getting AWS Instances information");
    return ec2.describeInstances(function (err, data) {
        if (err) {
            console.log("error in receiving instance information from EC2", err.stack);
            return Promise.reject("error in receiving instance information from EC2");
        } else {
            console.log("Total instances from EC2:", Object.keys(data["Reservations"]).length);
            return Promise.resolve(data);
        }
    });
};

在主叫方面,我做

getAwsInstancesInfo().then(data => {
    console.log("Total instances from EC2:", Object.keys(data["Reservations"]).length);
});

但是,它没有说出以下内容

index.js:12 Uncaught TypeError: Object(...)(...).then is not a function
    at InstanceSummary.componentDidMount (index.js:12)
    at ReactCompositeComponent.js:264
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponent.js:263
    at CallbackQueue.notifyAll (CallbackQueue.js:76)
    at ReactReconcileTransaction.close (ReactReconcileTransaction.js:80)
    at ReactReconcileTransaction.closeAll (Transaction.js:209)
    at ReactReconcileTransaction.perform (Transaction.js:156)
    at batchedMountComponentIntoNode (ReactMount.js:126)
    at ReactDefaultBatchingStrategyTransaction.perform (Transaction.js:143)
    at Object.batchedUpdates (ReactDefaultBatchingStrategy.js:62)
    at Object.batchedUpdates (ReactUpdates.js:97)
    at Object._renderNewRootComponent (ReactMount.js:319)
    at Object._renderSubtreeIntoContainer (ReactMount.js:401)
    at Object.render (ReactMount.js:422)
    at Object../src/index.js (index.js:21)
    at __webpack_require__ (bootstrap 0a6128d5488129446b34:669)
    at fn (bootstrap 0a6128d5488129446b34:87)
    at Object.0 (registerServiceWorker.js:108)
    at __webpack_require__ (bootstrap 0a6128d5488129446b34:669)
    at bootstrap 0a6128d5488129446b34:715
    at bundle.js:719

我正在使用React.js而我的package.json看起来像

{
  "name": "myproject",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "aws-sdk": "^2.105.0",
    "material-ui": "^0.19.0",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-scripts": "1.0.12"
  },
  "scripts": {
    "api": "node src/api/index.js",
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

2 个答案:

答案 0 :(得分:1)

https://aws.amazon.com/ko/blogs/developer/support-for-promises-in-the-sdk/

AWS.Request对象支持promise()方法。请参阅此文档。

答案 1 :(得分:0)

根据@Kangsu的帮助,我所要做的只是

let getAwsInstancesInfo = function () {
    return ec2.describeInstances().promise();
};

那就是它。非常感谢@kangsu!