【发布时间】:2018-01-16 15:16:48
【问题描述】:
我已经开始研究如何使用 Promises,并首先将一个简单的函数放在一起并调用了几次。我需要对拒绝和解决进行全面检查。
- 这是“承诺”函数的正确方法吗?
- 这是处理拒绝和解决的正确方法吗?
-
我有什么完全错误的吗?
const Redis = require('ioredis'); const redis = new Redis({ port: 6379, host: '127.0.0.1' }); function checkValues(name, section) { return new Promise((resolve, reject) => { redis.multi() .sismember('names', name) .sismember('sections', section) .exec() .then((results) => { if(results[0][1] === 1 && results [1][1] ===1) { reject('Match on both.'); } else if(results[0][1] === 1 || results [1][1] ===1) { reject('Match on one.'); } else { redis.multi() .sadd('names', name) .sadd('sections', section) .exec() .then((results) => { // Lazy assumption of success. resolve('Added as no matches.'); }) // No catch needed as this would be thrown up and caught? } }) .catch((error) => { console.log(error); }); }); } // Call stuff. checkValues('barry', 'green') .then((result) => { // Added as no matches "resolve" message from 'barry', 'green' console.log(result); retutn checkValues('steve', 'blue'); }) .then((result) => { // Added as no matches "resolve" message from 'steve', 'blue' retutn checkValues('steve', 'blue'); }) .then((result) => { // Match on both "reject" message from 'steve', 'blue' console.log(result); }) .catch((error) => { console.log(error); });
【问题讨论】:
标签: javascript node.js promise