可以将承诺错误解决为高阶承诺吗 EX
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
template <typename T,typename U>
class KeyValuePair {
public:
KeyValuePair(T key, T value)
: _key{key}, _value{value} {}
T key() const {
return _key;
}
T value() const {
return _value;
}
string string(T key) {
return key.to_string();
}
private:
T _key;
T _value;
};
template <typename T, typename U>
ostream& operator<<(ostream& out, const KeyValuePair<T, U>& pair)
{
out << "{" << pair.key() << ":" << pair.value() << "}";
return out;
}
int main() {
KeyValuePair<int, bool> kvp1{ 1, true };
KeyValuePair<string, int> kvp2{ string("count"), 7 };
cout << "KVP1 = " << kvp1 << endl;
cout << "KVP2 = " << kvp2 << endl;
}
get_data_from_db可以调用其他异步函数。 拒绝并没有使错误返回更高的承诺
答案 0 :(得分:0)
由于await
也适用于非承诺,因此您可以保存整个Promise
构造:
const async_function = () => get_data_from_db();
(async()=>{
try {
//call async function
const data = await async_function();
console.log(data);
} catch (err) {
console.error(err.message);
}
})();
答案 1 :(得分:0)
可以兑现诺言
有时候还可以。将被拒绝的承诺视为“异步抛出”,并对其进行捕获
但是您的代码是反模式http://bluebirdjs.com/docs/anti-patterns.html#the-explicit-construction-anti-pattern
的示例const async_function = async (resolve, reject) => {
// some code
get_data_from_db
.then(data => resolve(null,data))
.catch(e => resolve(e, null)
}
您可以将其重写为:
const async_function = () =>
get_data_from_db()
.catch(e => e) // it will be resolved with e