2017-08-31 91 views
0

目前,AWS documentation有看起來像如何將基於回調的函數轉換爲基於Promise的函數?

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" 
    } 
} 
+0

你必須使用'new Promise' - 承諾不會改變這個回調中的'return'毫無意義的事實。但真的只是使用內置的承諾支持:-) – Bergi

回答

0

基於@Kangsu的幫助下,我不得不做的是

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

就是這樣。非常感謝@ kangsu!