许诺是充当未来价值的占位符的对象。您的
parse()函数返回该Promise对象。通过将
.then()处理程序附加到promise,您可以在promise中获得未来的价值:
function parse(){ return new Promise(function(resolve, reject){ request('https://bitskins.com/api/v1/get_account_balance/?api_key='+api+'&pre='+pre, function (error, response, body) { // in addition to parsing the value, deal with possible errors if (err) return reject(err); try { // JSON.parse() can throw an exception if not valid JSON resolve(JSON.parse(body).data.available_balance); } catch(e) { reject(e); } }); });}parse().then(function(val) { console.log(val);}).catch(function(err) { console.err(err);});这是异步代码,因此,仅能通过
.then()处理程序来获得承诺的价值。
修改清单:
.then()
在返回的promise对象上添加处理程序以获取最终结果。.catch()
在返回的Promise对象上添加处理程序以处理错误。err
在request()
回调中添加对值的错误检查。- 添加try / catch,
JSON.parse()
因为如果无效的JSON可能抛出异常



